<template>
  <view class="chat-box">
    <!-- 消息列表区域 -->
    <scroll-view 
      class="chat-box__messages"
      scroll-y
      :scroll-into-view="lastMessageId"
    >
      <view 
        v-for="(msg,index) in messages"
        :key="index"
        :id="'msg-'+msg.id"
        :class="['chat-box__message', msg.role]"
      >
        <image :src="msg.avatar" class="avatar"/>
        <view class="content">{{msg.content}}</view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="chat-box__input">
      <input 
        v-model="content"
        type="text"
        placeholder="说点什么..."
        confirm-type="send"
        @confirm="onSend"
      />
      <button 
        :disabled="!content" 
        @tap="onSend"
      >发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  messages: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['send'])

const content = ref('')
const lastMessageId = computed(() => {
  const messages = props.messages
  return messages.length ? `msg-${messages[messages.length-1].id}` : ''
})

const onSend = () => {
  if(!content.value) return
  emit('send', content.value)
  content.value = ''
}
</script>

<style lang="scss">
.chat-box {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #F5F5F5;
  
  &__messages {
    flex: 1;
    padding: 20rpx;
  }
  
  &__message {
    display: flex;
    margin-bottom: 30rpx;
    
    &.user {
      flex-direction: row-reverse;
      
      .content {
        margin: 0 20rpx 0 100rpx;
        background: #007AFF;
        color: #fff;
        
        &:after {
          right: -20rpx;
          border-left-color: #007AFF;
        }
      }
    }
    
    &.assistant .content {
      margin: 0 100rpx 0 20rpx;
      background: #fff;
      
      &:after {
        left: -20rpx;
        border-right-color: #fff;
      }
    }
    
    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
    }
    
    .content {
      padding: 20rpx;
      border-radius: 12rpx;
      position: relative;
      
      &:after {
        content: '';
        position: absolute;
        top: 24rpx;
        border: 10rpx solid transparent;
      }
    }
  }
  
  &__input {
    display: flex;
    padding: 20rpx;
    background: #fff;
    
    input {
      flex: 1;
      height: 72rpx;
      padding: 0 20rpx;
      border-radius: 36rpx;
      background: #F5F5F5;
    }
    
    button {
      width: 120rpx;
      height: 72rpx;
      margin-left: 20rpx;
      border-radius: 36rpx;
      background: #007AFF;
      color: #fff;
      font-size: 28rpx;
      
      &[disabled] {
        background: #ccc;
      }
    }
  }
}
</style>